package com.aaa.service.Impl;

import com.aaa.entity.Role;
import com.aaa.entity.Users;
import com.aaa.mapper.UserMapper;
import com.aaa.service.UserService;
import com.aaa.util.DefaultMsg;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, Users> implements UserService {
    @Autowired
    private UserMapper usersMapper;

    @Override
    public List<Users> listAll(String keyword) {

        List<Users> list = usersMapper.listAll(keyword);

        list.forEach((item)-> {
            item.setRoles(usersMapper.listRole(item.getUid()));
        });
        return list;
    }

    @Override
    public DefaultMsg saveOrUpdate(Users users, String rolesId) {
        DefaultMsg defaultMsg = new DefaultMsg();
        Integer result;
        users.setPassword(new BCryptPasswordEncoder().encode("123456"));
        if (users.getUid() == null) {
            result = usersMapper.add(users);
        } else {
            result = usersMapper.update(users);
//           删除用户角色
            usersMapper.deleteRole(users.getUid());
        }
//        拆分roles
        String[] split = rolesId.split(",");
        for (String rid : split) {
            usersMapper.addRole(users.getUid(), Long.valueOf(rid));
        }

        if (result != null || result != 0) {
            return defaultMsg;
        } else {
            defaultMsg.setMsg("添加或修改失败");
            return defaultMsg;
        }
    }

    @Override
    public DefaultMsg delete(Long uid) {
        DefaultMsg defaultMsg = new DefaultMsg();
        Integer delete = usersMapper.delete(uid);
//        删除用户角色
        Integer deleteRole = usersMapper.deleteRole(uid);
        if (delete == 0 || delete == null||deleteRole == 0 || deleteRole == null) {
            defaultMsg.setSuccess(0);
            defaultMsg.setMsg("删除失败");
        }
        return defaultMsg;
    }

    @Override
    public Integer getUserRolesCountByUid(Long uid) {
        return usersMapper.getUserRolesCountByUid(uid);
    }

    @Override
    public int delRole(Long uid, Long rid) {
        return usersMapper.delRole(uid, rid);
    }

    @Override
    public int resetPassword(Long uid) {
//        密码使用默认密码
        return usersMapper.resetPassword(uid, new BCryptPasswordEncoder().encode("123456"));
    }

    @Override
    public List<Role> listAllRole() {
        return usersMapper.listAllRole();
    }
}
